package query_processing.email;

import crawling.email.EmailCrawler;
import data.Term;
import data.email.EmailStatistic;
import data.email.EmailStatistic.EmailDocumentStatistic;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import query_processing.QueryProcessor;

/**
 *
 * @author Muqtafi Akhmad
 */
public class EmailQueryProcessor implements QueryProcessor {

    @Override
    public void doProcessQuery(String indexDirectory, String fieldName, String tokenString, boolean isCompressed) {
        FileWriter fstream = null;
        try {
            // load file mapping antara id dokumen dengan id message
            EmailCrawler crawler = new EmailCrawler();
            crawler.readDocMappingFile(indexDirectory, isCompressed);
            HashMap<Integer, String> mapping = crawler.getDocumentMapping();
            // membaca term dari dalam directory
            long startTime = System.currentTimeMillis(), endTime;
            Term resultTerm = new Term(tokenString);
            resultTerm.setStatistic(new EmailStatistic(resultTerm.getTermString()));
            File indexDir = new File(indexDirectory);
            File workerFolders[] = indexDir.listFiles();
            for (File workerFolder : workerFolders) {
                if (workerFolder.isDirectory()) {
                    // cek apakah ada file index dari term dalam worker
                    File checkFile = new File(resultTerm.getPath(workerFolder.getAbsolutePath()));
                    if (checkFile.exists()) {
                        // load token
                        Term tempToken = new Term(tokenString);
                        tempToken.loadTerm(checkFile.getAbsolutePath());
                        resultTerm.getStatistic().merge(tempToken.getStatistic());
                    }
                }
            }
            endTime = System.currentTimeMillis();
            System.out.println("## Query execution finished , elapsed time " + (endTime - startTime) + " mili seconds");
            // tulis file text hasil query
            String fileName = "ARM-" + fieldName + "-" + tokenString + ".txt";
            fstream = new FileWriter(fileName);
            BufferedWriter out = new BufferedWriter(fstream);
            EmailStatistic stat = (EmailStatistic) resultTerm.getStatistic();
            EmailDocumentStatistic fieldStatistic = stat.getDocStatistic(fieldName);
            if (fieldStatistic != null) {
                HashMap<Integer, ArrayList<Integer>> relatedDocs = fieldStatistic.getRelatedDocs();
                out.write(tokenString + " FIELD=" + fieldName + " DF=" + relatedDocs.size() + "\n");
                Iterator it = relatedDocs.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry pairs = (Map.Entry) it.next();
                    Integer docID = (Integer) pairs.getKey();
                    ArrayList<Integer> positions = (ArrayList<Integer>) pairs.getValue();
                    String line = "MSG-ID=" + mapping.get(docID) + " TF=" + positions.size();
                    for (Integer pos : positions) {
                        line += " " + pos;
                    }
                    line += "\n";
                    out.write(line);
                }
            } else {
                out.write("Term not found \n");
            }
            out.close();
            fstream.close();
        } catch (IOException ex) {
            Logger.getLogger(EmailQueryProcessor.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
        }
    }
}